package cn.szsys.integration.advice;

import cn.szsys.integration.ex.BusinessException;
import cn.szsys.integration.ex.MissingRequireParamException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.WebRequest;

/**
 * @author Ryan
 * @since 2025-03-11
 **/
@RestController
public class CustomErrorController implements ErrorController {
    private static final Logger logger = LoggerFactory.getLogger(CustomErrorController.class);

    private final ErrorAttributes errorAttributes;

    public CustomErrorController(ErrorAttributes errorAttributes) {
        this.errorAttributes = errorAttributes;
    }

    @GetMapping("/error")
    public void handleErrorGet(WebRequest request) throws Throwable {
        exceptionHandler(request);
    }

    @PostMapping("/error")
    public void handleErrorPost(WebRequest request) throws Throwable {
        // 获取 Filter 抛出的异常
        exceptionHandler(request);
    }


    private void exceptionHandler(WebRequest request) throws Throwable {
        // 获取 Filter 抛出的异常
        Throwable throwable = errorAttributes.getError(request);

        if (throwable instanceof BusinessException businessException) {
            logger.warn("业务异常捕获: {}", businessException.getMessage());
            // 将异常抛出，交由 @ControllerAdvice 处理
            throw businessException;
        } if (throwable instanceof MissingRequireParamException missingRequireParamException) {
            logger.warn("业务异常捕获: {}", missingRequireParamException.getMessage());
            // 将异常抛出，交由 @ControllerAdvice 处理
            throw missingRequireParamException;
        }else if (throwable != null) {
            logger.error("未知异常捕获", throwable);
            // 将异常抛出，交由 @ControllerAdvice 处理
            throw throwable;
        } else {
            logger.warn("未捕获到异常信息，可能为 404 或其他错误");
            throw new Exception("请求失败，未捕获到异常信息");
        }
    }

}
